const { json } = require('body-parser');
const fs = require('fs');
const path = require('path');


const p = path.join(path.dirname(process.mainModule.filename), 'data', 'cart.json');

 module.exports = class Cart{
     static addProduct(id, productsPrice){
         //获取之前的购物车
         fs.readFile(p, (err, fileContent)=>{
             let cart = {
                 products:[],
                 totalPrice:0
             }
             if(!err){
               cart = JSON.parse(fileContent);
             }
             //分析购物车，找到已存在的产品
             const existingProductIndex = cart.products.findIndex(prod => prod.id === id);
             const existingProduct = cart.products[existingProductIndex];
             let updateProduct;
             //3.添加产品/增加产品的数量
             if(existingProduct){
                 updateProduct = {...existingProduct};
                 updateProduct.quantity = updateProduct.quantity + 1;
                 cart.products = [...cart.products];
                 cart.products[existingProductIndex] = updateProduct;

             }else {
                 updateProduct = {id :id , quantity: 1};
                 cart.products = [...cart.products, updateProduct];
             }
             cart.totalPrice = cart.totalPrice + +productsPrice;
             fs.writeFile(p, JSON.stringify(cart),err =>{
                 console.log(err);
             })
         }) 
     }
     static deleteProduct(id, productPrice){
         fs.readFile(p, (err, fileContent)=>{
             if(err){
                 return;
             }
             const updateCart = {...JSON.parse(fileContent)};
             const product = updateProduct.products.find(prod => prod.id === id);
             const productQuantity = product.quantity;
             updateCart.products = updateCart.products.filter(prod=> prod.id !== id);
             updateCart.totalPrice = updateCart.totalPrice - productPrice * productQuantity;
             fs.writeFile(p, JSON.stringify(updateCart), err =>{
                 console.log(err);
             })
         })
     }
     static getCart(cb){
         fs.readFile(p, (err, fileContent)=>{
             const cart = JSON.parse(fileContent);
             if(err){
                 cb(null);
             }else {
                 cb(cart);
             }
         })
     }
 }